/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2007 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id: header,v 1.16.2.1.2.1 2007/01/01 19:32:09 iliaa Exp $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_mc.h"
#include "memcached.h"
#include "standard/php_string.h"
#include "standard/php_var.h"
#include "quicklz.c"

/* If you declare any globals in php_mc.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(mc)
*/

/* True global resources - no need for thread safety here */
//static int le_link;

extern  int le_link;

/* {{{ mc_functions[]
 *
 * Every user visible function must have an entry in mc_functions[].
 */
zend_function_entry mc_functions[] = {
	PHP_FE(mc_connect,NULL)
	PHP_FE(mc_set,NULL)
	PHP_FE(mc_get,NULL)
	PHP_FE(mc_delete,NULL)
	PHP_FE(mc_flush,NULL)
	PHP_FE(mc_quit,NULL)
	PHP_FE(mc_close,NULL)
	{NULL, NULL, NULL}	/* Must be the last line in mc_functions[] */
};
/* }}} */

/* {{{ mc_module_entry
 */
zend_module_entry mc_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
	STANDARD_MODULE_HEADER,
#endif
	"mc",
	mc_functions,
	PHP_MINIT(mc),
	PHP_MSHUTDOWN(mc),
	PHP_RINIT(mc),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(mc),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(mc),
#if ZEND_MODULE_API_NO >= 20010901
	"0.1", /* Replace with version number for your extension */
#endif
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_MC
ZEND_GET_MODULE(mc)
#endif

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("mc.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_mc_globals, mc_globals)
    STD_PHP_INI_ENTRY("mc.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_mc_globals, mc_globals)
PHP_INI_END()
*/
/* }}} */

/* {{{ php_mc_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_mc_init_globals(zend_mc_globals *mc_globals)
{
	mc_globals->global_value = 0;
	mc_globals->global_string = NULL;
}
*/
/* }}} */

static void _close_mc_link(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
	memcached_st *link = (memcached_st *)rsrc->ptr;
	memcached_quit(link);
}

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(mc)
{
	/* If you have INI entries, uncomment these lines 
	REGISTER_INI_ENTRIES();
	*/
	le_link=zend_register_list_destructors_ex(_close_mc_link,NULL,RESOURCE_TAG,module_number);

	//REGISTER_LONG_CONSTANT("YHM_MC_SERIALIZED",YHM_MC_SERIALIZED,CONST_CS | CONST_PERSISTENT);

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(mc)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(mc)
{
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(mc)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(mc)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "mc support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */


/* Remove the following function when you have succesfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_mc_compiled(string arg)
   Return a string to confirm that the module is compiled in */

static char* _qen(char *value,int *qen_len){
	int len;
	char *src,*dst,*scratch;
	len = strlen(value);
	src = (char*) emalloc(len);
	src = value;
	dst = (char*) emalloc(len+400);
	scratch = (char*)emalloc(SCRATCH_COMPRESS);
	*qen_len = qlz_compress(src,dst,len,scratch);
	return dst;
}
	
static char* _qde(char *value){
	int len;
	char *src,*dst,*scratch;
	len = strlen(value);
	src = (char*)emalloc(len);
	src = value;
	len = qlz_size_decompressed(src);
	dst = (char*)emalloc(len);
	scratch = (char*)emalloc(SCRATCH_DECOMPRESS);
	len = qlz_decompress(src,dst,scratch);
	return dst;
}


static void _mc_connect(INTERNAL_FUNCTION_PARAMETERS)
{
    memcached_st *yhm_memc;
    memcached_return yhm_rc;
    char *hostname;
    long port;
    int s_len;
	int args = ZEND_NUM_ARGS();

    if(zend_parse_parameters(args TSRMLS_CC,"sl", &hostname,&s_len,&port)==FAILURE){
        WRONG_PARAM_COUNT;
    }

    yhm_memc = memcached_create(NULL);

    yhm_rc = memcached_server_add(yhm_memc,hostname,port);
    if(yhm_rc == MEMCACHED_SUCCESS){
        YHM_REGISTER_RESOURCE(yhm_memc);
    }else{
		RETURN_FALSE;
    }
}



PHP_FUNCTION(mc_connect)
{
	_mc_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}

static void yhm_mc_store(memcached_st * mc,char *key,int keylen,char *value,int  value_len,int times,int utui){

	//printf("%s\n",key);
	//printf("%d\n",value_len);
    memcached_set(mc,key,keylen,value,value_len,times,utui);

}


static void _mc_set(INTERNAL_FUNCTION_PARAMETERS)
{
    zval *mc_link,*value,*key;
    mc_resource *mccon;
    char *mcg,*real_key,*real_value,*comvalue;
	int comlen;
    int value_g,key_len,value_len;
    int flags = 0;
	int compress = 0;
	long expire = 0;
	int argc = ZEND_NUM_ARGS();
    memcached_return error;

	php_serialize_data_t value_hash;
	smart_str buf = {0};

    if(zend_parse_parameters(argc TSRMLS_CC,"rzz|ll",&mc_link,&key,&value,&compress,&expire)==FAILURE){
        WRONG_PARAM_COUNT;
    }else{
        YHM_FETCH_RESOURCE(mccon,mc_resource *,&mc_link);
		convert_to_string(key);
		real_key = Z_STRVAL_P(key);
		key_len = Z_STRLEN_P(key);		
		switch(Z_TYPE_P(value)){
			case IS_STRING:
			case IS_LONG:
			case IS_DOUBLE:
			case IS_BOOL:
					convert_to_string(value);
					real_value = Z_STRVAL_P(value);
					value_len = Z_STRLEN_P(value);
					break;
			default:
				 PHP_VAR_SERIALIZE_INIT(value_hash);
				 php_var_serialize(&buf,&value,&value_hash TSRMLS_CC);
				 PHP_VAR_SERIALIZE_DESTROY(value_hash);

				 if(!buf.c){
					RETURN_FALSE;
				 }
				 real_value = buf.c;
				 value_len = buf.len;
				 flags = 1;
				 break;			 
		}
		
		if(compress!=0){
			comvalue = _qen(real_value,&comlen);
			//printf("%d\n",*comlen);
			//printf("%s\n%s\n",_qde(comvalue),real_value);
			//comlen = strlen(comvalue);
			flags++;
		}else{
			comvalue = real_value;
			comlen = value_len;
		}
		yhm_mc_store((memcached_st *)mccon,real_key,key_len,comvalue,comlen,expire,flags);

		RETURN_TRUE;
    }

}


PHP_FUNCTION(mc_set)
{
	_mc_set(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}

static void _mc_get(INTERNAL_FUNCTION_PARAMETERS){
	zval *mc_link,*key;
	memcached_return error;
	mc_resource *mccon;
	char *real_key,*mcg;
	int flags=0,value_g,key_len;
	const unsigned char *tmp = NULL;
	int args = ZEND_NUM_ARGS();

	php_unserialize_data_t var_hash;

	if(zend_parse_parameters(args TSRMLS_CC,"rz",&mc_link,&key) == FAILURE){
		WRONG_PARAM_COUNT;
	}else{
		YHM_FETCH_RESOURCE(mccon,mc_resource *,&mc_link);
		convert_to_string(key);
		real_key = Z_STRVAL_P(key);
		key_len = Z_STRLEN_P(key);
		//printf("%d\n",key_len);					
		mcg = memcached_get((memcached_st *)mccon,real_key,key_len,&value_g,&flags,&error);
		//printf("%s\n",mcg);

		if(flags >= 2){
			//printf("%s\n",mcg);
			tmp =_qde(mcg);
			//tmp = mcg;
			flags = flags - 1;
		}else{
			tmp = mcg;
		}

		if(error == MEMCACHED_NOTFOUND || error != MEMCACHED_SUCCESS){
			RETURN_FALSE;
		}

		switch(flags){
			case 1:
				PHP_VAR_UNSERIALIZE_INIT(var_hash);
				if(!php_var_unserialize(&return_value,&tmp,tmp+value_g,&var_hash TSRMLS_CC)){
					PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
					zval_dtor(return_value);
					php_error_docref(NULL TSRMLS_CC,E_NOTICE,"Error %s,type:%d",mcg,value_g);
					RETURN_FALSE;
				}

				 PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
			break;
			case 0:
				RETURN_STRING(mcg,1);
			break;
		}
	}
}

PHP_FUNCTION(mc_get)
{
    _mc_get(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}

static void _mc_delete(INTERNAL_FUNCTION_PARAMETERS){
	
	memcached_return error;
	mc_resource *mccon;
	zval *mc_link,*key;
	char *real_key;
	int key_len,expire = 0,args = ZEND_NUM_ARGS();
	
	if(zend_parse_parameters(args TSRMLS_CC,"rz|l",&mc_link,&key,&expire) != FAILURE){
		YHM_FETCH_RESOURCE(mccon,mc_resource *,&mc_link);
		real_key = Z_STRVAL_P(key);
        key_len = Z_STRLEN_P(key);
		error = memcached_delete((memcached_st *)mccon,real_key,key_len,expire);
		if(error == MEMCACHED_SUCCESS){
			RETURN_TRUE;
		}else{
			RETURN_FALSE;
		}	
	}else{
		WRONG_PARAM_COUNT;
	}
}

PHP_FUNCTION(mc_delete){
    _mc_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}


static void _mc_flush(INTERNAL_FUNCTION_PARAMETERS){

    memcached_return error;
    mc_resource *mccon;
    zval *mc_link;
    int expire = 0,args = ZEND_NUM_ARGS();

    if(zend_parse_parameters(args TSRMLS_CC,"r|l",&mc_link,&expire) != FAILURE){
        YHM_FETCH_RESOURCE(mccon,mc_resource *,&mc_link);
        error = memcached_flush((memcached_st *)mccon,expire);
        if(error == MEMCACHED_SUCCESS){
            RETURN_TRUE;
        }else{
            RETURN_FALSE;
        }
    }else{
        WRONG_PARAM_COUNT;
    }
}

PHP_FUNCTION(mc_flush){
    _mc_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}


static void _mc_quit(INTERNAL_FUNCTION_PARAMETERS){

    mc_resource *mccon;
    zval *mc_link;
    int args = ZEND_NUM_ARGS();

    if(zend_parse_parameters(args TSRMLS_CC,"r",&mc_link) != FAILURE){
        YHM_FETCH_RESOURCE(mccon,mc_resource *,&mc_link);
        memcached_quit((memcached_st *)mccon);
		RETURN_TRUE;
	}else{
		WRONG_PARAM_COUNT;
	}
}

PHP_FUNCTION(mc_quit){
    _mc_quit(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}


PHP_FUNCTION(mc_close){
    mc_resource *mccon;
    zval *mc_link;
    int args = ZEND_NUM_ARGS();

    if(zend_parse_parameters(args TSRMLS_CC,"r",&mc_link) != FAILURE){
		if(zend_list_delete(Z_RESVAL_P(mc_link)) == FAILURE){
			RETURN_FALSE;
		}
		RETURN_TRUE;
	}
}


	
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and 
   unfold functions in source code. See the corresponding marks just before 
   function definition, where the functions purpose is also documented. Please 
   follow this convention for the convenience of others editing your code.
*/


/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
